Skip to content

fix(auth): preserve refresh tokens on HTTP 429 - #2875

Open
linye157 wants to merge 2 commits into
larksuite:mainfrom
linye157:fix/auth-refresh-rate-limit
Open

linye157 wants to merge 2 commits into
larksuite:mainfrom
linye157:fix/auth-refresh-rate-limit

Conversation

@linye157

@linye157 linye157 commented Oct 30, 2026 •

Copy link
Copy Markdown

Summary

A token-endpoint HTTP 429 can delete an otherwise usable stored login: plain-text responses enter the invalid-JSON retry-and-clear path, while JSON responses with an unknown code stop and clear immediately. Recognize HTTP 429 before reading or decoding the body, and use the existing bounded retry-and-preserve action.

Changes

  • Return a typed, retryable api/rate_limit error with HTTP code 429.
  • Add plain-text and JSON 429 regression cases, a successful retry/rotation control, and a negative control preserving the current handling of an earlier uncertain refresh.
  • Keep other HTTP statuses and refresh dispositions unchanged.
  • Document the refresh classification and scripted regression helpers.

Scope and limitations:

  • HTTP 429 is classified before reading or decoding the body, covering both plain-text and JSON responses. Repeated 429 responses preserve the stored token when no earlier attempt had an uncertain outcome; a successful retry stores the rotated token.
  • An earlier request that was written but produced an uncertain result still follows the existing retry/clear policy. A subsequent 429 does not override that uncertainty.
  • HTTP 5xx handling is unchanged. A server error does not establish whether a single-use refresh token was already consumed, so changing that policy needs separate evaluation alongside fix(auth): do not replay a refresh token after an ambiguous refresh #2840.
  • Retry count, timing, and backoff are unchanged; this PR does not add Retry-After support.

Test Plan

Validation of the original functional patch (before this comment-only follow-up):

  • go test -race ./internal/auth ./internal/credential ./internal/identitydiag ./cmd/auth -count=1
  • The two repeated-429 regressions fail on the original implementation with authentication/token_missing; both pass with this change.
  • Build, vet, formatting, go mod tidy (no module changes), pinned golangci-lint (0 issues), source guards, lint-module tests, and license check pass. Build/vet use GOFLAGS=-buildvcs=false because Go VCS discovery fails in this worktree.
  • Full make unit-test: 126 packages pass; eight fail. Two additional failures are worktree VCS discovery in internal/qualitygate/deptest and extension/command; both pass when rerun with GOFLAGS=-buildvcs=false. The remaining six packages have the same 31 failing test names as the checked base: Unix-socket restrictions, protected /root paths, and external DNS.
  • Live tenant refresh: not attempted; no controlled, cleanable way to force the token endpoint to return 429. The regression tests exercise GetValidAccessToken, retries, typed errors, and the isolated credential store through a scripted HTTP transport.

Follow-up validation:

  • git diff --check passes.
  • Removing full-line Go comments yields identical source before and after the follow-up in both changed files; executable code and assertions are unchanged.
  • Go tests and linters were not rerun for the comment-only follow-up: this session's container has no Go toolchain.

Related Issues

Summary by CodeRabbit

  • Bug Fixes
    • Refresh requests that receive an HTTP 429 rate-limit response can be retried without prematurely consuming the refresh credential.
    • Rate-limit responses are handled even when their response body is empty or cannot be decoded.
    • A later rate-limit response does not clear uncertainty from an earlier request that may have been processed.
    • A successful retry stores the rotated refresh credential.

@linye157
linye157 requested a review from liangshuo-1 as a code owner October 30, 2026 18:16
@github-actions github-actions Bot added the size/L Large or sensitive change across domains or core paths label Oct 30, 2026
@coderabbitai

coderabbitai Bot commented Oct 30, 2026 •

Copy link
Copy Markdown

Review in Change Stack →

No actionable comments were generated in the recent review.

Recent review info
Run configuration
  • Source mode: Auto
  • Repository: Unavailable
  • Branch: Unavailable
  • File: No configuration file from this repository applied
  • Commit: Unavailable
  • Layers: defaults
  • Review profile: CHILL
  • Plan: Advanced
  • Run ID: 7b7240c1-626c-4b58-b415-b6c3fbffa5f6
Commits

Reviewing files that changed from the base of the PR and between 37239d6 and ec7baa2.

Files selected for processing: 2
  • internal/auth/uat_client.go
  • internal/auth/uat_client_refresh_test.go
Files skipped from review as they are similar to previous changes: 2
  • internal/auth/uat_client.go
  • internal/auth/uat_client_refresh_test.go

Included review availability: This review used your included allowance. Your plan provides up to 10 included reviews per hour; 9 remain after this review.

Walkthrough

The refresh flow now detects HTTP 429 before reading or decoding the response body. It returns a retryable rate-limit error and preserves the stored refresh token. Tests cover repeated rate limits, an earlier uncertain transport failure, and a retry that succeeds.

Changes: Refresh rate-limit handling

Layer / File(s) Summary
HTTP 429 handling and retry validation
internal/auth/uat_client.go, internal/auth/uat_client_refresh_test.go
refreshOnce handles HTTP 429 before decoding the response body and preserves the stored refresh token. Tests cover plain-text and JSON rate limits, a rate limit after an uncertain transport failure, and a successful retry that stores the rotated refresh token.

Estimated code review effort: 2 (Simple) | ~10 minutes

Change: Bug fix · Severity of issue fixed: Medium

Merge Risk: Minimal · up to ec7ba

The HTTP 429 handling has no identified merge-blocking issue; proceed with normal checks.

Pre-merge checks: Passed 4 · Failed 1

Failed Failed checks: 1 warning

Check name Status Explanation Resolution
Linked Issues check Warning [#2869] is met for HTTP 429. The PR summary states that refreshOnce classifies HTTP 429 before body decoding, returns a retryable api/rate_limit error, and uses refreshRetryAndPreserve. The repo… Implement the #2865 HTTP 5xx requirement in refreshOnce before body decoding. Return the existing preserve action with a retryable error for status codes 500 and higher. Add plain-text and JSON 5xx regression cases that verify token prese…
Passed Passed checks: 4 passed
Check name Status Explanation
Title check Passed The title "fix(auth): preserve refresh tokens on HTTP 429" names the main change: HTTP 429 responses from the token endpoint no longer cause the stored refresh token to be cleared. The changeset class…
Description check Passed The description follows the repository template. It has a Summary that states the motivation and scope, a Changes list, a Test Plan with checklist items, and a Related Issues section that links #2869,…
Out of Scope Changes check Passed The reported changes are limited to internal/auth/uat_client.go and internal/auth/uat_client_refresh_test.go. The implementation supports HTTP 429 classification. The test helper, regression cases…
Docstring Coverage Passed Docstring coverage is 100.00% which is sufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff with cyclomatic complexity of at least 2. Documentat…
Full details: Title check

Explanation

The title "fix(auth): preserve refresh tokens on HTTP 429" names the main change: HTTP 429 responses from the token endpoint no longer cause the stored refresh token to be cleared. The changeset classifies 429 before body decoding and returns a retryable api/rate_limit error, and the tests cover that behavior. The title is short, specific, and follows a conventional-commit style.

Full details: Description check

Explanation

The description follows the repository template. It has a Summary that states the motivation and scope, a Changes list, a Test Plan with checklist items, and a Related Issues section that links #2869, #2865, #2860, and #2840. The Test Plan records which checks ran and which did not, including the unchecked full unit-test run and the live tenant refresh. The template's Test Plan asks for a manual lark-cli verification item. The description does not include that item, and the author does not explain its absence. This is a minor gap because the description is otherwise complete.

Full details: Out of Scope Changes check

Explanation

The reported changes are limited to internal/auth/uat_client.go and internal/auth/uat_client_refresh_test.go. The implementation supports HTTP 429 classification. The test helper, regression cases, retry-rotation case, uncertain-refresh control, and comments support the linked refresh behavior. No unrelated change is reported.

Full details: Docstring Coverage

Explanation

Docstring coverage is 100.00% which is sufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff with cyclomatic complexity of at least 2. Documentation-only edits and deletions within surviving functions are included; unchanged diff context and fully deleted functions are excluded. Analyzed 3 functions across 2 files.

Full details: Linked Issues check

Explanation

[#2869] is met for HTTP 429. The PR summary states that refreshOnce classifies HTTP 429 before body decoding, returns a retryable api/rate_limit error, and uses refreshRetryAndPreserve. The reported tests cover plain-text and JSON 429 responses, retry success, and the uncertain-refresh control. [#2865] is only partially met. Its expected behavior also requires retryable preservation for every HTTP 5xx response, with or without a JSON body. The PR states that HTTP 5xx handling remains unchanged and does not report 5xx implementation or regression coverage.

Resolution

Implement the #2865 HTTP 5xx requirement in refreshOnce before body decoding. Return the existing preserve action with a retryable error for status codes 500 and higher. Add plain-text and JSON 5xx regression cases that verify token preservation and the returned error classification. Keep the existing uncertain-outcome behavior unchanged.

Finishing Touches
Generate unit tests (beta)
  • Create a new PR
  • Autofix · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

Share

@YingzuoLiu

Copy link
Copy Markdown

Adding another anonymized reproduction from lark-cli v1.0.98 on macOS with Keychain storage.

Two isolated user configurations each encountered two consecutive HTTP 429 responses from /oauth/v3/token, less than 100 ms apart. Afterward, auth status reported the stored token as missing. The refresh tokens were still within their validity windows.

We did not capture stderr or response bodies, so we cannot confirm which token-clearing path was triggered.

PR #2875 appears to address token preservation on HTTP 429. However, immediate retries remain unchanged.

Would it make sense to track bounded backoff with Retry-After support as a separate follow-up, without blocking this PR? Tests could cover repeated 429s, missing or malformed Retry-After, and cancellation during the wait.

Our current workaround is to stagger initial refresh calls across configurations.

@linye157

linye157 commented Nov 2, 2026

Copy link
Copy Markdown
Author

@YingzuoLiu Thanks for the additional reproduction. It is consistent with the symptom this patch targets, though without stderr or response bodies we cannot identify which clearing path was taken.

Agreed that bounded backoff and Retry-After support should be tracked as a separate follow-up. This PR classifies HTTP 429 before body decoding and preserves the stored token across repeated 429s when there was no earlier uncertain refresh outcome. It leaves retry count and timing unchanged, so it does not address the immediate retries you observed.

The follow-up should cover repeated 429s, valid/missing/malformed Retry-After values, a bounded fallback delay, and cancellation during the wait. Keeping that separate would let the token-preservation fix be reviewed independently.

YingzuoLiu added a commit to YingzuoLiu/cli that referenced this pull request Nov 2, 2026
Retain linye157's original HTTP 429 token-preservation commits.
This dependency is not part of the independent backoff implementation.
Keep the follow-up draft until larksuite#2875 merges.
@yonedanorikuni0118

Copy link
Copy Markdown

Another reproduction on npm @larksuite/cli 1.0.98–1.0.99 (macOS, brand lark, DPoP, one self-built app, one user). The same refreshOnce path (parse the body without checking resp.StatusCode, refreshRetryAndClear on invalid JSON) is still on main.

The stored login was deleted 3 times in 6 days. Each time it was a single refresh that got two 429s from /oauth/v3/token about 100–160 ms apart, while refreshExpiresAt was still days away:

2026-11-05T09:00:13.541+09:00 path=/oauth/v3/token status=429  (lark-cli api GET ...)
2026-11-05T09:00:13.692+09:00 path=/oauth/v3/token status=429
2026-11-08T19:27:06.143+09:00 path=/oauth/v3/token status=429  (lark-cli base +record-list ...)
2026-11-08T19:27:06.304+09:00 path=/oauth/v3/token status=429
2026-11-10T16:49:55.060+09:00 path=/oauth/v3/token status=429  (lark-cli api GET ...)
2026-11-10T16:49:55.165+09:00 path=/oauth/v3/token status=429

In the same week there were 4 other refreshes where a single 429 was followed by a 200 on the retry (11/05 07:05, 11/06 18:44, 11/07 13:23, 11/10 10:46), and the login survived those.

One more data point on the impact: deleteStoredToken also deletes the token's DPoP key (dpop.KeyStore.Delete), so after the deletion there is no local way to recover. A full device-flow re-authorization is needed, and scheduled jobs that use user identity stop until someone approves it.

As far as I can tell, checking resp.StatusCode before parsing and preserving the token on 429, as this PR does, would have kept the login in all three cases.

Related: #2865, #2869

@zengyuzhi-ambr

Copy link
Copy Markdown

Another data point in support of this fix: we run lark-cli under a background daemon on employees' Macs (brand lark, one self-built app per person, user identity, one subprocess per call).

  • On 2026-11-11 16:15 (UTC+8), one machine on v1.0.98 hit the same path: refresh attempt 1/2 failed … token refresh returned invalid JSON: invalid character 'r', then need_user_authorization / token_missing. The user had to sign in again, and the scheduled job that needed the token silently failed until then.
  • On another machine (v1.0.99), ~/.lark-cli/logs/auth-*.log shows /oauth/v3/token returning 429 three times in two days:
    • 2026-11-10T16:14:13+08:00 logid 20261110161413E1A7516065EECA1D1EF8
    • 2026-11-10T16:14:19+08:00 logid 20261110161419C8CB2DD08CADD41E3B35
    • 2026-11-11T10:54:06+08:00 logid 2026111110540619950D9F62941F7170CC

We checked v1.0.100: refreshOnce in internal/auth/uat_client.go still parses the body as JSON before looking at the status code, so a 429 still ends in refreshRetryAndClear. Treating 429 as "not processed, keep the token, back off per Retry-After" as this PR does would fix it for us. Could a maintainer take a look?

In the meantime we added a check on our side that tells the user when their login disappears, but keeping the token is the real fix.

@yonedanorikuni0118

Copy link
Copy Markdown

Follow-up: this still happens on v1.0.100, the latest release (2026-11-10). That release does not include this PR, and refreshOnce in v1.0.100 still parses the body before checking resp.StatusCode.

The 4th deletion here had the same shape. A single refresh got two 429s 0.28 s apart, and refreshExpiresAt was still 7 days away:

2026-11-12T14:21:42.911+09:00 path=/oauth/v3/token status=429  (lark-cli base +record-list ...)
2026-11-12T14:21:43.192+09:00 path=/oauth/v3/token status=429

That makes 4 deletions in 8 days (11/05, 11/08, 11/10, 11/12) for one user. Each one stops our scheduled jobs that use user identity until someone approves a new device flow. This time that took about 2 hours.

Any chance this PR could make the next release?

@linye157

linye157 commented Nov 20, 2026 via email

Copy link
Copy Markdown
Author

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

size/L Large or sensitive change across domains or core paths

Projects

None yet

Development

Successfully merging this pull request may close these issues.

auth: a 429 from the Token Endpoint during refresh deletes a still-valid login

4 participants